package com.rightsidetech.http.controller.agentApp.store;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.config.RedisKeys;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.enums.ModifyName;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.commom.utils.HttpClient;
import com.rightsidetech.commom.utils.RedisUtils;
import com.rightsidetech.commom.utils.StringUtil;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.ModifyLog;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.dtos.request.store.AddSysStoreInfoReq;
import com.rightsidetech.system.dtos.request.store.StoreSearchReq;
import com.rightsidetech.system.dtos.request.store.UpdateSysStoreInfoReq;
import com.rightsidetech.system.dtos.response.store.StoreResp;
import com.rightsidetech.system.dtos.response.store.StoreSearchResp;
import com.rightsidetech.system.service.SysAgentInfoService;
import com.rightsidetech.system.service.SysStoreInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.rightsidetech.http.controller.agentApp.store
 * @ClassName: StoreController
 * @Author: yinj
 * @CreateTime: 2021/11/10 11:20
 */
@Slf4j
@RestController
@Api(tags = "代理商app-门店管理")
@RequestMapping("/agentApp/store")
@ShenyuSpringMvcClient(path = "/agentApp/store/**")
public class AgentAppStoreController extends BaseController {

    @Resource
    private SysStoreInfoService sysStoreInfoService;
    @Resource
    private SysAgentInfoService sysAgentInfoService;

    @Value("${storeCodeUrl}")
    private String storeCodeUrl;
    @Resource
    private RedisUtils redisUtils;

    @Value("${restapi.amap.addressUrl}")
    private String addressUrl;
    @Value("${restapi.amap.key}")
    private String amapKey;


    @Log
    @Token
    @GetMapping("/page")
    @ApiOperation("门店分页")
    public ResponseData<PageInfo<StoreResp>> page(StoreSearchReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long agentLoginId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreInfoService.storePage(req,agentInfoId);

    }

    @Log
    @Token
    @GetMapping("/search")
    @ApiOperation("门店下拉选")
    public ResponseData<List<StoreSearchResp>> storeSearch(String content){
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
       return sysStoreInfoService.search(content, agentInfoId,null);
    }

    @Log
    @Token
    @GetMapping("/open_search")
    @ApiOperation("开启中的门店下拉选")
    public ResponseData<List<StoreSearchResp>> open_search(String content){
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreInfoService.searchOpen(content, agentInfoId,null);
    }

    @Log
    @Token
    @ApiOperation("添加门店")
    @PostMapping("/add")
    @ModifyLog(serviceClass = SysStoreInfoService.class,modifyType = ModifyName.SAVE)
    public ResponseData add(@RequestBody AddSysStoreInfoReq request) throws Exception {
        ConstraintViolation validate = BeanValidator.validate(request);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long agentLoginId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(agentLoginId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        request.setSysAgentInfoId(agentInfoId);
        String maxStoreNo = getMaxStoreNo();
        request.setStoreNumber(maxStoreNo);
        request.setCodeImage(storeCodeUrl + maxStoreNo);
        request.setSysAgentInfoId(agentInfoId);
        Map map = new HashMap<>();
        map.put("key", amapKey);
        map.put("address", request.getAdress());

        String provice = null;
        String city = null;
        String area = null;

        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(HttpClient.sendGet(addressUrl, map));
        if (!StringUtil.isNullorEmpty(jsonObject) && jsonObject.getString("status").equals("1") && !StringUtil.isNullorEmpty(jsonObject.get("geocodes"))) {
            JSONArray jsonArray = jsonObject.getJSONArray("geocodes");
            com.alibaba.fastjson.JSONObject jsonObject2 = jsonArray.getJSONObject(0);

            if (!StringUtil.isNullorEmpty(jsonObject2.getString("location"))) {
                provice = jsonObject2.getString("province");
                city = jsonObject2.getString("city");
                area = jsonObject2.getString("district");
            } else {
                return ResponseData.fail("地址错误, 请重新输入地址");
            }
        } else {
            return ResponseData.fail("地址错误, 请重新输入地址");
        }

        return sysStoreInfoService.add(request,provice,city,area);

    }

    @Log
    @Token
    @PostMapping("/update")
    @ApiOperation("修改")
    @ModifyLog(serviceClass = SysStoreInfoService.class)
    public ResponseData update(@RequestBody UpdateSysStoreInfoReq request){
        ConstraintViolation validate = BeanValidator.validate(request);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        request.setSysAgentInfoId(agentInfoId);
        return sysStoreInfoService.update(request,null);

    }

    @ApiIgnore
    @Log
    @Token
    @PostMapping("/del")
    @ApiOperation("删除")
    @ApiOperationSupport(params = @DynamicParameters(name = "DelReq", properties = {
            @DynamicParameter(name = "id", value = "id", required = true, dataTypeClass = Long.class)
    }))
    @ModifyLog(serviceClass = SysStoreInfoService.class)
    public ResponseData del(@RequestBody JSONObject req){
        Long id = req.getLong("id");
        if (StringUtils.isEmpty(id)) {
            return ResponseData.fail(CodeIdEnum.IllegalParameter);
        }
        Long loginInfoId = Long.parseLong(getAttribute());
        //获取登录账号代理商id
        Long agentInfoId = sysAgentInfoService.findAgentInfoId(loginInfoId);
        if (StringUtils.isEmpty(agentInfoId)){
            return ResponseData.fail(CodeIdEnum.Expired);
        }
        return sysStoreInfoService.del(id,agentInfoId);
    }

    /**
     * 查询最大店铺号
     * @return
     */
    private synchronized String getMaxStoreNo(){
        Long incr = 1L;
        try {
            incr = redisUtils.getIncr(RedisKeys.YS_STORE_NO);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        if (incr == 1L){
            String maxStoreNo = sysStoreInfoService.getMaxStoreNo();
            if (StringUtil.notNullAndWhitSpace(maxStoreNo)){
                incr = Long.parseLong(maxStoreNo.replace("YSS", "")) + 1;
                redisUtils.setIncr(RedisKeys.YS_STORE_NO, incr);
            }
        }
        String fillBefore = StrUtil.fillBefore(incr.toString(), '0', 8);
        return "YSS" + fillBefore;
    }



}
